using Beauty.Net.MongoDB.Core;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace Beauty.Net.MongoDB;

/// <summary>
/// MongoDB服务依赖注入扩展
/// </summary>
public static class MongoDBServiceCollectionExtensions
{
    /// <summary>
    /// 添加MongoDB服务
    /// </summary>
    /// <param name="services">服务集合</param>
    /// <param name="configureOptions">配置选项</param>
    /// <returns>服务集合</returns>
    public static IServiceCollection AddMongoDBService(this IServiceCollection services, Action<MongoDBOptions> configureOptions)
    {
        // 注册配置选项
        if (configureOptions != null)
        {
            services.Configure(configureOptions);
        }
        else
        {
            services.Configure<MongoDBOptions>(options => { });
        }

        // 注册MongoDB服务
        services.AddSingleton<IMongoDBService>(provider =>
        {
            var options = provider.GetRequiredService<IOptions<MongoDBOptions>>().Value;
            return new MongoDBService(options);
        });

        return services;
    }

    /// <summary>
    /// 添加MongoDB服务
    /// </summary>
    /// <param name="services">服务集合</param>
    /// <param name="connectionString">连接字符串</param>
    /// <param name="databaseName">数据库名称</param>
    /// <param name="connectTimeoutSeconds">连接超时时间（秒）</param>
    /// <param name="useSsl">是否启用SSL</param>
    /// <returns>服务集合</returns>
    public static IServiceCollection AddMongoDBService(
        this IServiceCollection services,
        string connectionString,
        string databaseName = "BeautyDB",
        int connectTimeoutSeconds = 30,
        bool useSsl = false)
    {
        return services.AddMongoDBService(options =>
        {
            options.ConnectionString = connectionString;
            options.DatabaseName = databaseName;
            options.ConnectTimeoutSeconds = connectTimeoutSeconds;
            options.UseSsl = useSsl;
        });
    }
}